/**
 * 
 */
package com.edocbase.desktop.mht;

import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @author X61
 *
 */
public class MhtUrlParser {
	
	public static String parse(String html,Map<String, String> resouceCache){
		Document doc = Jsoup.parse(html);
		Elements media = doc.select("[src]");
		parseUrl(doc, media, resouceCache);
		Elements imports = doc.select("link[href]");
		parseUrl(doc, imports, resouceCache);
		Elements links = doc.select("a[href]");
		parseUrl(doc, links, resouceCache);
		Elements actions = doc.select("form[action]");
		parseUrl(doc, actions, resouceCache);
		return doc.html();
	}
	private static void parseUrl(Document doc, Elements resourceList,
			Map<String, String> resouceCache) {
		for (Element res : resourceList) {
			String resAbsUrl = "";
			String resUrl = "";
			String tagName = res.tagName().toLowerCase();
			if (tagName.equals("img") || tagName.equals("script")
					|| tagName.equals("input")) {
				resAbsUrl = res.attr("abs:src");
				if (resouceCache.containsKey(resAbsUrl)) {
					resUrl = resouceCache.get(resAbsUrl);
					res.attr("src", resUrl);
				} 
			} else if (tagName.equals("a")) {
				resAbsUrl = res.attr("abs:href");
				if (resouceCache.containsKey(resAbsUrl)) {
					resUrl = resouceCache.get(resAbsUrl);
					res.attr("href", resUrl);
				} 
			} else if (tagName.equals("link")) {
				resAbsUrl = res.attr("abs:href");
				if (resouceCache.containsKey(resAbsUrl)) {
					resUrl = resouceCache.get(resAbsUrl);
					res.attr("href", resUrl);
				}
			} else if (tagName.equals("form")) {
				resAbsUrl = res.attr("abs:action");
				if (resouceCache.containsKey(resAbsUrl)) {
					resUrl = resouceCache.get(resAbsUrl);
					res.attr("action", resUrl);
				}				
			} else if (tagName.equals("frame") || tagName.equals("iframe")) {
				resAbsUrl = res.attr("abs:src");
				if (resouceCache.containsKey(resAbsUrl)) {
					resUrl = resouceCache.get(resAbsUrl);
					res.attr("src", resUrl);
				}					
			} else {
				System.out.printf("No Process %s\r\n", tagName);
			}
		}

	}
}
